const fs = require('fs');
const path = require('path');
const promisify = require('util').promisify;
const writeFile = promisify(fs.writeFile);
const readFile = promisify(fs.readFile);

const dbPath = path.join(__dirname, './storage/db.json')

exports.getDb = async () => {
  try {
    const data = await readFile(dbPath, 'utf-8')
    return JSON.parse(data)
  } catch (error) {
    throw new Error('getDb' + ' : ' + error);
  }
}

exports.saveDb = async (db) => {
  try {
    const data = JSON.stringify(db, null, "  ")
    await writeFile(dbPath, data)
  } catch (error) {
    throw new Error('saveDb' + ' : ' + error);
  }

}

exports.saveParameter = async (data) => {
  try {
    let db = await this.getDb()
    if (db.parameter != undefined) {
      if (db.parameter.length != 0) {
        db.parameter.pop()
      }
      if (data != undefined) {
        db.parameter.push(data)
        await this.saveDb(db)
      } else {
        console.log('savaParameter failed : data is undefined')
      }
    } else {
      console.log('savaParameter failed : db.parameter is undefined')
    }
  } catch (error) {
    throw new Error('saveParameter' + ' : ' + error);
  }
}

exports.getParameter = async () => {
  try {
    let db = await this.getDb()
    if (db.parameter != undefined) {
      if (db.parameter.length != 0) {
        let data = db.parameter[0]
        return data
      } else {
        console.log('getParameter failed : db have no parameter')
      }
    } else {
      console.log('getParameter failed : db.parameter is undefined')
    }
  } catch (error) {
    throw new Error('getParameter' + ' : ' + error);
  }
}

exports.deletePrintLog = async (index) => {
  try {
    let db = await this.getDb()
    if(db.upload.length != 0){
      if(index <= db.upload.length){
        db.upload.splice(index,1)
        await this.saveDb(db)
      }
    }
  } catch (error) {
    throw new Error('deletePrintLog' + ' : ' + error);
  }
}